import { Component } from 'react';
import { connect } from 'dva';
import withRouter from 'umi/withRouter';
import PropTypes from 'prop-types';
import { Divider, Modal, Card, Table } from 'antd';
import { routerRedux } from 'dva/router';

import style from './Orders.css';
import { getStatusDesc, getRefundStatusDesc } from './utils';
import { PAGE_SIZE } from 'globalConstants';
import DetailModal from './DetailModal';
import RefundModal from './RefundModal';
import SearchForm from './SearchForm';
import CustomPagin from 'components/CustomPagin';

let filters = {};
class Orders extends Component {
  constructor(props) {
    super(props);
    this.state = {
      detailOrderId: null,
      refundOrder: null,
    };
  }

  // 申请退款
  handleRefund = values => {
    const { remark } = values;
    const { dispatch } = this.props;
    const { id } = this.state.refundOrder;

    Modal.confirm({
      title: `申请退款确认`,
      content: '你确定此订单要走入退款流程吗？',
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch({
          type: 'orders/refund',
          payload: {
            id,
            remark,
          },
        }).then(({ code }) => {
          if (!code) {
            this.handleToggleRefund(null);
          }
        });
      },
    });
  };

  // 确认已经退款
  handleConfirmRefund = id => {
    const { dispatch } = this.props;

    Modal.confirm({
      title: `订单退款确认`,
      content: '你确定此订单已经完成退款了吗？',
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch({
          type: 'orders/confirmRefund',
          payload: {
            id,
          },
        });
      },
    });
  };

  // 取消退款
  handleCancelRefund = id => {
    const { dispatch } = this.props;

    Modal.confirm({
      title: `订单退款取消`,
      content: '你确定此订单取消退款吗？',
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch({
          type: 'orders/cancelRefund',
          payload: {
            id,
          },
        });
      },
    });
  };

  handlePageChange = page => {
    const { uri } = this.props;

    filters = { ...filters, page };
    this.props.dispatch(
      routerRedux.push({
        pathname: uri,
        query: filters,
      })
    );
  };

  handleToggleRefund = refundOrder => {
    this.setState({
      refundOrder,
    });
  };

  handleToggleDetail = detailOrderId => {
    this.setState({
      detailOrderId,
    });
  };

  handleSearch = params => {
    const { uri } = this.props;
    const page = 1;

    filters = { ...params, page };
    this.props.dispatch(
      routerRedux.push({
        pathname: uri,
        query: filters,
      })
    );
  };

  render() {
    const { detailOrderId, refundOrder } = this.state;
    const { items: dataSource, loading, total, page: current, parent } = this.props;
    const filter = this.props.location.query;

    let columns = null;
    if (parent === 'list') {
      // 订单列表
      columns = [
        {
          title: '订单号',
          dataIndex: 'tradeNo',
          key: 'tradeNo',
          render: (invoice, record) => {
            return (
              <a
                href="javascript: void(0)"
                onClick={e => {
                  e.preventDefault();
                  this.handleToggleDetail(record.id);
                }}>
                {invoice}
              </a>
            );
          },
        },
        {
          title: '订单金额(¥)',
          dataIndex: 'totalAmount',
          key: 'totalAmount',
        },
        {
          title: '商品名称',
          dataIndex: 'product',
          key: 'product',
        },
        {
          title: '订单状态',
          dataIndex: 'status',
          key: 'status',
          render: status => {
            if (parent === 'list') {
              return (
                <span className={style[`item-status-${status}`]}>{getStatusDesc(status)}</span>
              );
            }
          },
        },
        {
          title: '下单时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
        },
        {
          title: '支付时间',
          dataIndex: 'paidAt',
          key: 'paidAt',
        },
        {
          title: '操作',
          key: 'operation',
          render: (text, record) => (
            <span className={style['operation']}>
              {getStatusDesc(record.status) === '支付成功' && (
                <a
                  href="javascript: void(0)"
                  onClick={e => {
                    e.preventDefault();
                    this.handleToggleRefund(record);
                  }}>
                  申请退款
                </a>
              )}
            </span>
          ),
        },
      ];
    } else {
      // 退款列表
      columns = [
        {
          title: '订单号',
          dataIndex: 'tradeNo',
          key: 'tradeNo',
          render: invoice => {
            return <span>{invoice}</span>;
          },
        },
        {
          title: '退款金额(¥)',
          dataIndex: 'refundAmount',
          key: 'refundAmount',
        },
        {
          title: '商品名称',
          dataIndex: 'product',
          key: 'product',
        },
        {
          title: '订单状态',
          dataIndex: 'status',
          key: 'status',
          render: status => {
            return <span>{getRefundStatusDesc(status)}</span>;
          },
        },
        {
          title: '下单时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
        },
        {
          title: '支付时间',
          dataIndex: 'paidAt',
          key: 'paidAt',
        },
        {
          title: '退款备注',
          dataIndex: 'remark',
          key: 'remark',
        },
        {
          title: '操作',
          key: 'operation',
          render: (text, record) => (
            <span className={style['operation']}>
              {getRefundStatusDesc(record.status) === '已申请' && (
                <>
                  <a
                    href="javascript: void(0)"
                    onClick={e => {
                      e.preventDefault();
                      this.handleConfirmRefund(record.id);
                    }}>
                    确认退款
                  </a>
                  <Divider type="vertical" key="line" />
                  <a
                    href="javascript: void(0)"
                    onClick={e => {
                      e.preventDefault();
                      this.handleCancelRefund(record.id);
                    }}>
                    取消退款
                  </a>
                </>
              )}
            </span>
          ),
        },
      ];
    }

    return (
      <div className={style['normal']}>
        {detailOrderId !== null && (
          <DetailModal
            onCancel={() => {
              this.handleToggleDetail(null);
            }}
            orderId={detailOrderId}
          />
        )}
        {refundOrder !== null && (
          <RefundModal
            onOk={this.handleRefund}
            onCancel={() => {
              this.handleToggleRefund(null);
            }}
            tradeNo={String(refundOrder.tradeNo)}
          />
        )}

        <Card className={style['form']}>
          <SearchForm
            key={Math.random()}
            parent={parent}
            filter={filter}
            onSearch={this.handleSearch}
          />
        </Card>
        <Table
          bordered
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          rowKey={record => record.id}
          pagination={false}
        />
        <CustomPagin
          total={total}
          current={current}
          pageSize={PAGE_SIZE}
          onChange={this.handlePageChange}
        />
      </div>
    );
  }
}

if (process.env.UMI_ENV !== 'prod') {
  Orders.propTypes = {
    dispatch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    items: PropTypes.array.isRequired,
    page: PropTypes.number.isRequired,
    uri: PropTypes.string.isRequired,
    parent: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    location: PropTypes.object.isRequired,
  };
}

Orders.defaultProps = {
  dispatch: () => {},
  total: 0,
  items: [],
  page: 1,
  uri: '/orders/list',
  parent: 'list',
  loading: false,
  location: {},
};

function mapStateToProps(state, { uri, parent }) {
  const { items, total, page } = state.orders;
  const effects = state.loading.effects;
  const loading = parent === 'list' ? effects['orders/fetchList'] : effects['orders/fetchRefunds'];

  return {
    items,
    total,
    page,
    uri,
    parent,
    loading,
  };
}

export default withRouter(connect(mapStateToProps)(Orders));
